import process from 'child_process';
//发现设备
export const devices = ()=>{
    return new  Promise((resolve, reject) => {
        process.exec("adb devices",function (error, stdout, stderr) {
            if(error){
                console.log(stderr)
                reject({
                    stderr: stderr,
                    error: error
                });
                return;
            }
            console.log(stdout)
           let androidDevices =  stdout.trim().split("\r\n").splice(1,1).map(item =>{
                let obj = {};
                let line = item.split("\t");
                obj.label = line[0];
                return obj;
            })
            console.log("当前设备：",androidDevices)
            resolve(androidDevices);
        })
    })
}
//截屏
export const screencap = (sid,pngPath) => {
    const cmd = "adb -s "+sid+" shell screencap -p /sdcard/"+pngPath;
    console.log("screencap:",cmd);
    return new Promise((resolve, reject)=>{
        process.exec(cmd,function (error, stdout, stderr) {
            if(error){
                console.log(stderr)
                reject({
                    stderr: stderr,
                    error: error
                });
                return;
            }
            console.log(stdout) 
            resolve(pngPath);
        })
    });
   
}
//拉取设备截屏图片
export const pullPng = (sid,pngPath) => {
    const cmd = "adb -s "+sid+" pull /sdcard/"+pngPath+" ./"+sid+"/"+pngPath;
    console.log("screencap:",cmd);
    return new Promise((resolve, reject)=>{
        process.exec(cmd,function (error, stdout, stderr) {
            if(error){
                console.log(stderr)
                reject({
                    stderr: stderr,
                    error: error
                });
                return;
            }
            console.log(stdout)
            resolve(pngPath);
        })
    });
}

//清理手机中的照片
export const  rmFile =(sid,pngPath) => {
    const cmd = "adb -s "+sid+" shell rm -rf /sdcard/"+pngPath;
    console.log("screencap:",cmd);
    return new Promise((resolve, reject)=>{
        process.exec(cmd,function (error, stdout, stderr) {
            if(error){
                console.log(stderr)
                reject({
                    stderr: stderr,
                    error: error
                });
                return;
            }
            console.log(stdout)
            resolve(pngPath);
        })
    });
}


export const deletePhoneImg = (deleteTask) =>{
    rmFile(deleteTask.sid,deleteTask.pngPath).then(res =>{
        console.log("删除图片成功",deleteTask);
    }).catch(err =>{
        console.log("删除图片失败",deleteTask);
    });
}